package dp.mobile.comm.worker;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import android.bluetooth.BluetoothSocket;
import android.util.Log;

class Courier extends WorkerBase {
	private InputStream mInputStream = null;
	private OutputStream mOutputStream = null;
	private ObjectOutputStream mObjectSender;
	private DataOutputStream mDataSender;
	private ObjectInputStream mObjectReceiver;
	
	public Courier(BluetoothHandler handler , BluetoothSocket sock) {
		super(handler);
		mSocket = sock;
		
		try {
			mInputStream = mSocket.getInputStream();
			mOutputStream = mSocket.getOutputStream();
			mObjectSender = new ObjectOutputStream(mOutputStream);
			mDataSender = new DataOutputStream(mOutputStream);
			mObjectReceiver = new ObjectInputStream(mInputStream);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		if (mInputStream != null) {
			DataInputStream in = new DataInputStream(mInputStream);
			while (!mCanceled) {
				try {
					int objId = in.readInt();
					Log.i("this" , "OBJECT RECEIVED");
					//if (mEventHandler != null) {
						//Log.i("this" , mEventHandler.toString());
						Log.i("this" , "CALL HANDLER WITH obj id = " + String.valueOf(objId));
						//mEventHandler.onObjectReceived(objId, mInputStream);
						mHandler.objectReceived(objId, mObjectReceiver);
					//}
				} catch (IOException e) {
					/*if (mEventHandler != null && !mCanceled) {
						mEventHandler.onConnectionFailed();
						Log.i("this" , "COURIER EX");
					}*/
					if (!mCanceled) mHandler.connectionFailed();
					break;
					// TODO Auto-generated catch block
					//e.printStackTrace();
				}
			}
		}
	}
	
	public void sendObject(Object o) {
		if (mOutputStream != null) {
			try {
				//ObjectOutputStream oo = new ObjectOutputStream(mOutputStream);
				//oo.writeObject(o);
				mObjectSender.writeObject(o);
				mObjectSender.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void sendInt(int val) {
		if (mOutputStream != null) {
			//DataOutputStream out = new DataOutputStream(mOutputStream);
			
			try {
				//out.writeInt(val);
				mDataSender.writeInt(val);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void cancel() {
		// TODO Auto-generated method stub
		mCanceled = true;
		try {
			mSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
